<script lang="ts" setup>
import type { TableColumnCtx } from 'element-plus';

import type { Dict } from '@croco/framework/types';

import { h, nextTick, onBeforeMount, onMounted, reactive, ref } from 'vue';

import { useUserStore } from '@croco/framework/stores';

import dayjs from 'dayjs';
import { ElText } from 'element-plus';

import { getDictTrim } from '#/api';
import { DataTable } from '#/components/data-table';

const { userInfo } = useUserStore();
const dataTableRef = ref<InstanceType<typeof DataTable>>();
const enums = reactive<{
    status: Array<Dict> | undefined;
}>({
    status: undefined,
});

const formatter = (row: any, column: TableColumnCtx) => {
    switch (column.property) {
        case 'status': {
            const dict = enums[column.property]?.find((item) => item.value === row[column.property]);
            return h(ElText, { type: dict?.listClass || 'info' }, { default: () => dict?.label || '--' });
        }
        case 'timeFrame': {
            return row.loginTime;
        }
        default: {
            return row[column.property];
        }
    }
};

const columns = [
    { prop: 'ipaddr', label: '登录地址' },
    { prop: 'location', label: '登录地点' },
    { prop: 'browser', label: '浏览器' },
    { prop: 'os', label: '操作系统' },
    { prop: 'status', label: '操作结果', column: { align: 'center', formatter } },
    { prop: 'timeFrame', label: '登录时间', column: { formatter } },
];

onBeforeMount(() => {
    getDictTrim(['sys_common_status']).then((rs) => {
        enums.status = rs[0] ?? [];
    });
});

onMounted(() => {
    nextTick(() => {
        dataTableRef.value?.refresh({
            params: {
                username: userInfo.username,
                timeFrame: [dayjs(new Date(Date.now() - 7 * 24 * 60 * 60 * 1000)).format('YYYY-MM-DD HH:mm:ss'), dayjs(new Date()).format('YYYY-MM-DD HH:mm:ss')].join(','),
            },
        });
    });
});
</script>

<template>
    <el-tabs model-value="first" class="log-tabs">
        <el-tab-pane name="first">
            <template #label>
                <span style="font-size: 20px">近7天登录记录</span>
            </template>
            <DataTable ref="dataTableRef" :columns="columns" api="/system/log/login" :pagination="false" index lazy />
        </el-tab-pane>
    </el-tabs>
</template>

<style></style>
